<template>
  <div class="flex">
    <div class="outline-left" :class="[activeFlag?'':'active']">
      <div tit="catalog" class="mind-corner-content">
        <div class="corner-title">
          <div class="label fb fz16">
             <div class="flex">
               <nuxt-link :to="'/note/detail/'+cnote.id"><img v-lazy="cnote.img" style="width: 86px;height: 60px;border-radius: 8px"></nuxt-link>
               <div class="ml15">
                 <nuxt-link :to="'/note/detail/'+cnote.id"><h1 class="fz16 fb">{{ cnote.title }}</h1></nuxt-link>
                 <div class="fz12 c666 fn mt5">
                   <span title="浏览数"><i class="iconfont icon-eye mr5 ml5 pr tp2"></i><span>{{cnote?.viewcount}}</span> </span>
                   <span title="创建时间"><i class="iconfont icon-shijian mr5 ml5"></i><span>{{cnote?.createTime}}</span></span>
                 </div>
               </div>
             </div>
          </div>
        </div>
        <div class="uni-list-bar"></div>
        <div  class="outline-catalog scroll mt10" v-if="chapterList && chapterList.length > 0">
          <div  class="catalog-node-element" v-for="(item,index) in chapterList"  :key="item.id">
            <div class="catalog-node-self">
              <div  class="catalog-node-title fb fz14 flex1" :class="[chapterIndex==index?'active':'']">第{{(index+1) < 10 ?'0'+(index+1):(index+1)}}章：
                <input title="序号" class="input-lg" style="text-align: center;width: 40px;margin-right: 5px;" @click="handleEditChapter(item,index)"  @blur="handleStatusChapter(item,'sorted',item.sorted,index)" v-model="item.sorted"/>
                <input title="0免费 1收费" class="input-lg" style="text-align: center;width: 40px;margin-right: 5px;" @click="handleEditChapter(item,index)"  @blur="handleStatusChapter(item,'free_flag',item.freeFlag,index)" v-model="item.freeFlag"/>
                <input class="input-lg" style="text-indent: 0.5em;width: 180px;" @focus="handleEditChapter(item,index)"  @click="handleEditChapter(item,index)"  v-model="item.title" @blur="handleStatusChapter(item,'title',item.title,index)"/></div>
              <div class="btnbox">
                <i class="iconfont icon-tianjia- fz20 pr tp2" @click="handleAddLesson(item,index)"></i>
                <i class="iconfont icon-bianji fz20 pr tp2" @click="handleEditChapter(item,index)"></i>
                <i class="iconfont icon-fuzhi" @click="handleCopyChapter(item,index)"></i>
                <i class="iconfont icon-unlock" v-if="item.status==1" @click="handleStatusChapter(item,'status',0,index)"></i>
                <i class="iconfont icon-lock" v-if="item.status==0" @click="handleStatusChapter(item,'status',1,index)"></i>
                <i class="iconfont icon-cuowu" @click="handleDelChapter(item,index)"></i>
                <i v-if="item.expand" @click="handleExpandLesson(item,index)" class="iconfont icon-fangxiang_jiantoufangxiang-xiangshang fz22 fb pr tp2"></i>
                <i v-else @click="handleExpandLesson(item,index)"  class="iconfont icon-fangxiang_jiantoufangxiang-xiangxia fz22 fb pr tp2"></i>
              </div>
            </div>
            <div class="category-node-child" style="margin-left: 28px;" v-if="item.expand && item.children">
               <div v-for="(citem,cindex) in item.children" class="catalog-node-self">
                 <div class="catalog-node-title flex1" :class="[chapterIndex==index && lessonIndex==cindex?'active':'']">{{(cindex+1) < 10 ?'0'+(cindex+1):(cindex+1)}}：
                   <input title="序号" class="input-lg" style="text-align: center;width: 40px;margin-right: 5px;"   @click="handleEditLesson(citem,index,cindex)" @blur="handleStatusLesson(citem,'sorted',citem.sorted,index,cindex)" v-model="citem.sorted"/>
                   <input title="0免费 1收费"  class="input-lg" style="text-align: center;width: 40px;margin-right: 5px;"  @focus="handleEditLesson(item,index,cindex)"  @click="handleEditLesson(citem,index,cindex)" @blur="handleStatusLesson(citem,'free_flag',citem.freeFlag,index,cindex)" v-model="citem.freeFlag"/>
                   <input class="input-lg" style="text-indent: 0.5em;width:228px;"  @focus="handleEditLesson(citem,index,cindex)"  @click="handleEditLesson(citem,index,cindex)" v-model="citem.title" @blur="handleStatusLesson(citem,'title',citem.title,index,cindex)"/></div>
                 <div class="btnbox">
                   <i class="iconfont icon-bianji fz20 pr tp2" @click="handleEditLesson(citem,index,cindex)"></i>
                   <i class="iconfont icon-fuzhi" @click="handleCopyLesson(citem,index,cindex)"></i>
                   <i class="iconfont icon-unlock" v-if="citem.status==1" @click="handleStatusLesson(citem,'status',0,index,cindex)"></i>
                   <i class="iconfont icon-lock" v-if="citem.status==0" @click="handleStatusLesson(citem,'status',1,index,cindex)"></i>
                   <i class="iconfont icon-cuowu" @click="handleDelLesson(citem,index,cindex)"></i>
                 </div>
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="outline-body" :class="[activeFlag?'active':'']">
      <div class="outline-head" style="margin-left: 0px;position: sticky">
        <div class="head-left-nav head-nav">
          <span title="收起" @click="handleExpand" v-if="activeFlag" class="closed ol-icons fz20 iconfont icon-zhankai pr tp1"></span>
          <span title="收起" @click="handleExpand" v-else class="closed ol-icons fz20 iconfont icon-shouqi pr tp1"></span>
          <div  class="node-title outline-title" title="章">{{editObj.chapterTitle}}</div>
          <span class="mr5 ml5" v-if="editObj.lessonId > 0">/</span>
          <div  v-if="editObj.lessonId" class="node-title outline-title" title="小节">{{editObj.lessonTitle}}</div>
        </div>
        <div class="head-nav head-right-nav">
          开始自动保存了：{{timercount%3 + 1}}s
          <button  @click.prevent="handleAllSave" class="btn ml15">点击保存</button>
          <a :href="'/note/base?id='+cnote.id"   class="btn ml15">返回基础信息</a>
          <button  @click.prevent="handleOpenDidlog" class="btn ml15">设置视频</button>
          <button  @click.prevent="handleRefreshCache" class="btn ml15">刷新缓存</button>
          <a :href="'/note/detail/'+cnote.id" target="_blank"><span title="预览" class="closed ol-icons fz20 iconfont icon-eye ml5"></span></a>
        </div>
      </div>
      <div  @paste="paste" id="test-editor"></div>
      <ul id="left-float-menu" class="left-float-menu" :class="[activeFlag?'active':'']">
        <li class="menu-item" title="展开和收起"
            @click="handleExpand"
            title-pos="right"><span class="ol-icons iconfont" :class="[activeFlag?'icon-zhankai':'icon-shouqi']"></span></li>
<!--        <li class="menu-item"  title-pos="right" title="展开大纲">-->
<!--          <span class="ol-icons iconfont icon-a-dagang1"></span>-->
<!--        </li>-->
        <li class="menu-item"  @click="handleAddChapter"  title-pos="right" title="添加章"><span
            class="ol-icons iconfont icon-tianjia-"></span></li>
      </ul>
    </div>
    <div id="copyhtml" style="position: fixed;top:-1000px;">
      课程标题：《{{cnote.title}}》<br/>
      课程地址：https://www.study512.com/note/detail/{{cnote.id}}<br/>
      平台来源：学习512-致力于帮助有梦想的年轻人获取学习价值<br/>
      商业转载请联系作者获得授权，非商业转载请注明出处。
    </div>
    <teleport to="body">
      <settingvideo :edit-obj="editObj" :clist="chapterList" ref="settingRef"></settingvideo>
    </teleport>
  </div>
</template>
<script setup>
import settingvideo from "@/pages/note/settingvideo.vue";
import Clipboard from "clipboard";
const platformStore = useStore.platformState()
let testEditor = null;
var submitFileFlag = false
const router = useRouter()
const imgs = ref([])
const activeFlag = ref(false)
const chapterList = ref([])
const chapterIndex = ref(-1)
const lessonIndex = ref(-1)
const cnote = ref({})
let timer = null
const timercount = ref(0)
const modemark = ref("chapter")
const editObj = ref({chapterTitle:"",chapterId:"",noteId:"",lessonId:"",lessonTitle:"",videoid:[]})
const settingRef = ref({})

const handleOpenDidlog = async () => {
  settingRef.value.handleOpen(cnote.value.id, chapterList.value)
}


// 刷新缓存
const handleRefreshCache = async ()=>{
  await useRefreshCache(cnote.value.id)
  useMessage().success("清除成功!")
}

// 编辑课程
const handleEditorNoteVideo = async()=>{
  try {
    const resp = await useLoadNoteUpdateVideoApi({
      "id": cnote.value.id ,
      "videoid":  cnote.value.videoid,
      "panLink":cnote.value.panLink,
      "panPwd":cnote.value.panPwd,
      "title":cnote.value.title,
      "img":cnote.value.img,
      "specialId":cnote.value.specialId
    })
    useMessage().success("修改成功!")
  }catch (e){
    useMessage().error(e.message)
  }
}

// 复制
const handleClipboardText = (e) => {
  const clipboard = new Clipboard('.copy-btn')
  // 复制成功
  clipboard.on('success', () => {
    useMessage().success('内容已复制到剪切板，可粘贴')
    // 释放内存
    clipboard.destroy()
  })
  // 复制失败
  clipboard.on('error', () => {
    useMessage().error('代码复制失败')
    // 释放内存
    clipboard.destroy()
  })
}

const handleExpand = ()=>{
  activeFlag.value = !activeFlag.value
  document.querySelector(".CodeMirror-wrap").style.width = "50%"
  document.querySelector(".editormd-preview").style.width = "50%"
}

const handleExpandLesson = (item,index)=>{
  chapterIndex.value = index
  lessonIndex.value = -1
  item.expand = !item.expand
}


const paste = function (event) {
  var cdata = (event.clipboardData || window.clipboardData);
  var items = cdata.items;
  if (items && items.length) {
    try {
      if (submitFileFlag) {
        useMessage().error("别太着急，慢一点!");
        return;
      }
      submitFileFlag = true
      var reader = new FileReader();
      var file = items[0].getAsFile()
      try {
        reader.readAsDataURL(file);
        reader.onload = function (event) {
          var formData = new FormData();
          formData.append('editormd-image-file', file)
          var xhr = new XMLHttpRequest();
          xhr.addEventListener("load", uploadComplete, false);
          xhr.addEventListener("error", uploadFailed, false);
          xhr.open('POST', "http://localhost:8089/api/v1/oss/upload/note");
          xhr.send(formData);
          function uploadComplete(evt) {
            var json = evt.target.responseText
            json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")");
            if (json.success == 1){
              testEditor.replaceSelection("![](" + json.url + ")");
              useMessage().success("粘贴成功")
              handleSetintervalSave()
              submitFileFlag = false;
            }
          }
          function uploadFailed() {
            submitFileFlag = false;
            useMessage().error("上传失败！请重试！");
          }
        }
      } catch (e) {
        submitFileFlag = false;
      }
    } catch (err) {
      submitFileFlag = false;
    }
  }
}

const handleLoadData = async ()=>{
  const resp = await useFindChapterLessons(router.currentRoute.value.query.id);
  chapterList.value = resp.data
}

const handleLoadDetail = async ()=>{
  const resp = await useLoadNoteDetail(router.currentRoute.value.query.id);
  cnote.value = resp.data
  cnote.value.id = router.currentRoute.value.query.id
  useHead({
    title:cnote.value.title
  })
  chapterList.value = resp.data.chapterList
  editObj.value.noteId = resp.data.id
  editObj.value.chapterTitle = resp.data.title
  if(resp.data.chapterList && resp.data.chapterList.length > 0) {
    handleEditChapter(resp.data.chapterList[0], 0)
  }
  platformStore.setHeaderFlag(true)
}

//添加章
const handleAddChapter = async()=>{
  await useLoginDialog()
  testEditor.setMarkdown("# 标题")
  editObj.value.chapterId = ""
  editObj.value.lessonId = ""
  editObj.videoid = []
  handleAddChapterMain()
}

//添加章
const handleAddChapterMain = async()=>{
  var sorted = chapterList.value?.length || 0 + 1
  const resp = await useChapterSave({noteId:cnote.value.id,noteTitle:cnote.value.title,title:"未知",sorted:sorted,mdcontent:testEditor.getMarkdown(),htmlcontent:testEditor.getHTML()})
  editObj.value.chapterTitle = "未知"
  editObj.value.noteId = cnote.value.id
  editObj.value.chapterId = resp.data.id
  editObj.value.videoid = ""
  editObj.value.lessonId = ""
  editObj.value.lessonTitle = ""
  chapterIndex.value =  chapterList.value?.length || 0
  lessonIndex.value = -1
  handleSetintervalSave()
  handleLoadData()
}

// 添加小节
const handleAddLesson = debounce(async (item,index)=>{
  await useLoginDialog()
  chapterIndex.value = index
  testEditor.setMarkdown("# 标题")
  editObj.videoid = []
  editObj.value.chapterTitle = item.title
  editObj.value.noteId = item.noteId
  editObj.value.chapterId = item.id
  var sorted = item.children.length + 1
  const resp = await useLessonSave({chapterId:item.id,title:"未知",sorted:sorted,noteId:cnote.value.id,noteTitle:cnote.value.title,chapterTitle:item.title,mdcontent:testEditor.getMarkdown(),htmlcontent:testEditor.getHTML()})
  editObj.value.lessonId = resp.data.id
  editObj.value.lessonTitle = "未知"
  lessonIndex.value = item.children.length
  handleSetintervalSave()
  handleLoadData()
},600)


// 编辑章
const handleEditChapter= async(item,index)=>{
  await useLoginDialog()
  if(chapterIndex.value == index && lessonIndex.value == -1){
    return;
  }
  chapterIndex.value = index
  lessonIndex.value = -1
  modemark.value = "chapter"
  editObj.value.chapterId = item.id
  editObj.value.chapterTitle = item.title
  editObj.value.noteId = item.noteId
  editObj.value.videoid = item.videoid?JSON.parse(item.videoid):[]
  editObj.value.lessonId = ""
  editObj.value.lessonTitle = ""
  var resp  = await useChapterGetById(item.id,cnote.value.id)
  testEditor.setMarkdown(resp.data.mdcontent)
  handleSetintervalSave()
}

const handleSetintervalSave = ()=>{
  if(timer){
    timercount.value = 0
    clearInterval(timer)
  }
  timer = setInterval(()=>{
    timercount.value++
    if(timercount.value >0 &&  timercount.value % 3 == 0){
      handleAllSave()
    }
  },1000)
}

// 编辑节
const handleEditLesson= async(item,index,cindex)=>{
  await useLoginDialog()
  if(chapterIndex.value == index && lessonIndex.value == cindex){
    return;
  }
  chapterIndex.value = index
  lessonIndex.value = cindex
  modemark.value = "lesson"
  item.expand = true
  editObj.value.chapterId = item.chapterId
  editObj.value.chapterTitle = item.chapterTitle
  editObj.value.noteId = item.noteId
  editObj.value.lessonId = item.id
  editObj.value.lessonTitle = item.title
  editObj.value.videoid = item.videoid?JSON.parse(item.videoid):[]
  var resp  = await useLessonGetById(item.id,cnote.value.id)
  testEditor.setMarkdown(resp.data.mdcontent)
  handleSetintervalSave()
}


// 复制章
const handleCopyChapter= debounce(async (item,index)=>{
  await useLoginDialog()
  const resp = await useChapterCopyData(item.id,cnote.value.id)
  editObj.value.chapterTitle = resp.data.title
  editObj.value.noteId = cnote.value.id
  editObj.value.chapterId = resp.data.id
  editObj.value.lessonId = ""
  editObj.value.lessonTitle = ""
  item.expand = true
  chapterIndex.value = index + 1
  lessonIndex.value = -1
  testEditor.setMarkdown(resp.data.mdcontent)
  handleSetintervalSave()
  handleLoadData()
},600)

// 状态修改
const handleStatusChapter= async (item,field,status,index)=>{
  await useLoginDialog()
  chapterIndex.value = index
  lessonIndex.value = -1
  await useChapterUpdateStatus({id:item.id,field:field,value:status,noteId:cnote.value.id})
  editObj.value.chapterTitle = item.title
  handleLoadData()
}

// 删除章
const handleDelChapter= debounce(async (item,index)=>{
  useDialog().warning({
    content: "你确定要删除吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      await useChapterRemoveByID({id:item.id,noteId:item.noteId})
      handleEditChapter(chapterList.value[index-1],index-1)
      if(editObj.value.chapterId == item.id){
        editObj.value = {chapterTitle:cnote.value.title}
        testEditor.setMarkdown("")
      }
      handleLoadData()
    },
  });
},600)


// 复制节
const handleCopyLesson= async (item,index,cindex)=>{
  const resp = await useLessonCopyData(item.id,cnote.value.id)
  editObj.value.chapterTitle = resp.data.chapterTitle
  editObj.value.noteId = cnote.value.id
  editObj.value.chapterId = resp.data.chapterId
  editObj.value.lessonId = resp.data.id
  editObj.value.lessonTitle = resp.data.title
  chapterIndex.value = index
  lessonIndex.value = cindex + 1
  testEditor.setMarkdown(resp.data.mdcontent)
  handleSetintervalSave()
  handleLoadData()
}

// 状态修改节
const handleStatusLesson = async (item,field,status,index,cindex)=>{
  chapterIndex.value = index
  lessonIndex.value = cindex
  await useLessonUpdateStatus({id:item.id,field:field,value:status,noteId:cnote.value.id})
  editObj.value.lessonTitle = item.title
  handleLoadData()
}

// 删除节
const handleDelLesson= debounce(async (item,index,cindex)=>{
  useDialog().warning({
    content: "你确定要删除吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      await useLessonRemoveByID({id:item.id,noteId:item.noteId})
      handleEditLesson(chapterList.value[index].children[cindex-1],index,cindex-1)
      if(editObj.value.lessonId == item.id){
        editObj.value = {chapterTitle:cnote.value.title}
        testEditor.setMarkdown("")
      }
      handleLoadData()
    },
  });
},600)

const handleAllSave = () => {
  if(editObj.value.chapterId && !editObj.value.lessonId) {
    if (testEditor.getMarkdown()) {
      useChapterUpdateContent({
        id: editObj.value.chapterId,
        noteId: editObj.value.noteId,
        mdcontent: testEditor.getMarkdown(),
        htmlcontent: testEditor.getHTML()
      })
      useMessage().success("保存成功!")
    }
  }

  if(editObj.value.chapterId && editObj.value.lessonId) {
    if (testEditor.getMarkdown()) {
      useLessonUpdateContent({
        id: editObj.value.lessonId,
        noteId: editObj.value.noteId,
        mdcontent: testEditor.getMarkdown(),
        htmlcontent: testEditor.getHTML()
      })
      useMessage().success("保存成功!")
    }
  }
}

useHead({
  title: "添加课程",
})

onMounted(()=>{
    document.addEventListener("keydown",function (e) {
      if (e.ctrlKey && e.key === 's') {
            handleAllSave()
            e.preventDefault();
        }
    })

    // 选中的内容替换
    //testEditormd.replaceSelection("$$$$$$$$$");
    // 在光标处插入
    //testEditormd.insertValue("????");
    // testEditor.getMarkdown();       // 获取 Markdown 源码
    // testEditor.getHTML();           // 获取 Textarea 保存的 HTML 源码
    // testEditor.getPreviewedHTML();  // 获取预览窗口里的 HTML，在开启 watch 且没有开启 saveHTMLToTextarea 时使用
    testEditor = editormd("test-editor", {
      width: "100%",
      fontSize: "14px",
      height : "calc(100vh - 80px)",
      placeholder:"请输入笔记正文内容...",
      syncScrolling: "single",
      path: "/editormd/lib/",
      saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
      // [TOCM]  [TOC] 自动生成目录
      tocm: true,
      tocContainer: "",
      tocDropdown: false,
      tocStartLevel: 1,     // Parse beginning of H2, Default value 1
      emoji: true,
      tex: true,                   // 开启科学公式TeX语言支持，默认关闭
      flowChart: true,             // 开启流程图支持，默认关闭
      sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
      //图片上传
      imageUpload: true,
      imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
      imageUploadURL: "http://localhost:8089/api/v1/oss/upload/note", // 对接后端请求
      onload: function () {
        handleLoadDetail()
      },
      delay:1000,
      onchange: function (e) {

      },
      /*指定需要显示的功能按钮*/
      toolbarIcons: function () {
        return ["undo", "redo", "|", "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "image", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "list-ul", "list-ol", "|", "link", "reference-link", "code", "code-block", "table", "datetime", "|", "goto-line", "watch", "preview", "fullscreen",  "|", "testIcon", "|", "layoutmd"]
      },
      toolbarIconTexts: {
        testIcon: "模板",  // 如果没有图标，则可以这样直接插入内容，可以是字符串或HTML标签
        layoutmd: "<a href='https://www.kuangstudy.com/bbs/1356475333565587458' target='_blank'>MarkDown指南</a>"
      },
      toolbarHandlers: {
        testIcon: function (cm, icon, cursor, selection) {
          // 替换选中文本，如果没有选中文本，则直接插入
          cm.replaceSelection(document.getElementById("template").value);
          // 如果当前没有选中的文本，将光标移到要输入的位置
          if (selection === "") {
            cm.setCursor(cursor.line, cursor.ch + 1);
          }
        },
        layoutmd: function (cm, icon, cursor, selection) {

        },
      },
      onfullscreen: function () {
      },
      onfullscreenExit: function () {
      },
      onwatch:function(){
      }
    });
})

onUnmounted(()=>{
  if(timer)clearInterval(timer);
  timercount.value = 0
})

definePageMeta({
  middleware: ["md-auth"],
  layout: "socialadd"
})
</script>
<style scoped>
.catalog-node-title input{border:1px solid #eee;height: 28px;line-height: 28px;}
</style>